﻿using System;

using System.Text;
using System.IO;
using System.Windows.Forms;

namespace Utils
{
    public static class FileHelper
    {
        /// <summary>
        /// 读文件
        /// </summary>
        /// <param name="filePath"></param>
        public static string ReadFile(string filePath)
        {
            //根据datetime找出要读的文件的路径
            //string filePath = "E:\\" + fileName;
            if (!File.Exists(filePath))
            {
                MessageBox.Show("您要查找的文件不存在:" + filePath);
                return null;
            }
            string result = string.Empty;
            //文件实例化streamreader对象
            StreamReader sr = new StreamReader(filePath, Encoding.GetEncoding("utf-8"));
            //调用readertoend 方法读取选中文件的全部内容
            result = sr.ReadToEnd();
            //关闭当前文件读取流
            sr.Close();
            return result;
        }

        /// <summary>
        /// 根据时间创建文件
        /// </summary>
        /// <param name="filePath"></param>
        public static void CreateFile(string filePath)
        {
            FileInfo fileInfo = new FileInfo(filePath);
            if (!fileInfo.Exists)
            {
                fileInfo.Create();

            }
            else
            {
                MessageBox.Show("文件已存在");
            }
        }
        /// <summary>
        /// 创建文件夹
        /// </summary>
        /// <param name="floderName"></param>
        public static void CreateFloder(string floderName)
        {
            if (!Directory.Exists(floderName))
            {
                Directory.CreateDirectory(floderName);
            }
        }

        /// <summary>
        /// 写文件
        /// </summary>
        /// <param name="content"> </param>
        /// <param name="filePath"> 定义要写入到的文件名路径</param>  
        public static void WriteToFile(string content, string filePath, FileMode fm)
        {
            try
            {
                FileStream fileStream = new FileStream(filePath, fm, FileAccess.Write);
                StreamWriter sw = new StreamWriter(fileStream, Encoding.UTF8);

                sw.WriteLine(content);
                sw.Close();
                fileStream.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// 获得当前目录
        /// </summary>
        /// <returns></returns>
        public static string RootPath()
        {
            string path = Application.StartupPath;
            return path;
        }
    }

}
